package com.ruoyi.app.service.impl;

import com.ruoyi.app.service.SmsService;
import com.ruoyi.app.utils.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 验证码发送时间
     */
    private static String code_time_prefix = "sms:time:";

    /**
     * 验证码
     */
    private static String code_prefix = "sms:code";


    @Override
    public Object sendCode(String phone) {
        //验证码间隔发送时间检查
        checkSpacing(phone);

        String code = smsCode();
        System.out.println("发送验证码：" + phone + ":" + code);

        // TODO: 2020/11/8 测试放开
//        Assert.isTrue(SmsUtil.sendCode(phone, code), "发送验证码失败，请联系管理员！");

        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        // 设置 发送验证码时间
        valueOperations.set(code_time_prefix + phone, String.valueOf(System.currentTimeMillis()), 70, TimeUnit.SECONDS);
        // 存储验证码
        valueOperations.set(code_prefix + phone, code, 300, TimeUnit.SECONDS);
        return true;
    }


    @Override
    public void verifyCode(String phone, String voucher) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String code = valueOperations.get(code_prefix + phone);
        Assert.hasText(code, "验证码不存在！");
        // TODO: 2020/11/8 测试放开
//        Assert.isTrue(code.equals(voucher), "验证码输入错误！");
        redisTemplate.delete(code_prefix + phone);
    }


    /**
     * 验证码间隔发送时间检查
     *
     * @param account
     * @param
     */
    private void checkSpacing(String account) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String number = valueOperations.get(code_time_prefix + account);
        if (!StringUtils.isEmpty(number)) {
            if ((System.currentTimeMillis() - Long.parseLong(number)) / 1000 < 60) {
                throw new IllegalArgumentException("发送验证码过于频繁，请稍后再试！");
            }
        }
    }


    /**
     * 创建验证码
     *
     * @return
     */
    public static String smsCode() {
        String random = (int) ((Math.random() * 9 + 1) * 100000) + "";
        return random;
    }


}
